<?php
/**
 * @ClassName: Merchant
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-09 10:21
 * @Version: V1.0.0
 */

namespace app\api\controller\agent;

use app\api\controller\Api;
use app\common\enum\CommonEnum;
use app\common\enum\MerchantEnum;
use app\common\logic\MemberLogic;
use app\common\model;
use think\Db;

class Merchant extends Api
{
    /**
     * 入驻商户列表
     * @return \think\response\Json
     */
    function list()
    {
        $keyword = input('keyword', '');
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];
        $where[] = ['parent_id', '=', $this->user_id];

        if ($keyword) {
            $where[] = ['merchant_short_name|contact_name|contact_phone|street_address|license_name|store_name', 'like', '%' . $keyword . '%'];
        }

        $list = model\Merchant::where($where)->limit($skip, $limit)->order('create_time desc')->select();
        $sql = model\Merchant::getLastSql();
//        var_dump($sql);

        foreach ($list as &$item) {
            $item['store_logo'] = $item['store_logo'] ? replace_url($item['store_logo']) : replace_url('/static/images/logo.png');
            $item['status_str'] = CommonEnum::examineText($item['status']);
            $item['store_type_str'] = MerchantEnum::storeTypeText($item['user_type']);
            $item['store_num'] = model\Store::where('merchant_id', $item['id'])->count();
        }

        $result = [
            'data' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 商户入驻
     * @return \think\response\Json
     */
    function add()
    {
        $data = input();

        $member = model\Member::where('mobile', $data['contact_phone'])->find();
        if ($member) {
            $member_id = $member['id'];
            $merchant = model\Merchant::where('member_id', $member_id)->find();
            if ($merchant) {
                return json(['code' => 0, 'msg' => '该手机号已绑定过商户']);
            }
        } else {
            $member_id = (new MemberLogic())->createMember($data['contact_phone'], $this->userInfo['member_id'], 2, 0, $data['email']);
        }

        Db::startTrans();
        try {
            $arr = passCrypt(env('default_password'));
            $add_data = [
                'username' => $data['contact_phone'],
                'password' => $arr[0],
                'salt' => $arr[1],
                'avatar' => '/static/images/avatar.png',
                'member_id' => $member_id,//商户管理员
                'parent_id' => $this->user_id,//商户的上级是代理
                'merchant_type' => 2,//商户类型，1小微，2企业，3个体
                'merchant_short_name' => $data['merchant_short_name'],
                'contact_name' => $data['contact_name'],
                'contact_phone' => $data['contact_phone'],
                'email' => $data['email'],
                'user_type' => $data['user_type'],
                'store_name' => $data['store_name'],
                'status' => 4,//店铺状态：-1已禁用，0待审核，1已通过，2已驳回，3锁定，4申请中
                'business_status' => 0,//营业状态，0休息，1营业
                'create_time' => date_now(),
            ];

            $merchant_id = model\Merchant::insertGetId($add_data);

            if ($merchant_id) {
                $store_data = [
                    'username' => $data['contact_phone'],
                    'password' => $arr[0],
                    'salt' => $arr[1],
                    'avatar' => '/static/images/avatar.png',
                    'merchant_id' => $merchant_id,
                    'member_id' => $member_id,//店铺管理员
                    'store_name' => $data['store_name'],
                    'contact_name' => $data['contact_name'],
                    'status' => 4,//店铺状态：-1已禁用，0待审核，1已通过，2已驳回，3锁定，4申请中
                    'business_status' => 0,//营业状态，0休息，1营业
                    'user_type' => $data['user_type'],
                    'is_first_one' => 1,//商户入住时创建首个门店
                    'create_time' => date_now(),
                ];

                $res = model\Store::create($store_data);
                if ($res) {
                    Db::commit();
                    return json(['code' => 1, 'msg' => '入驻成功']);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            var_dump($e->getMessage());
            trace($e);
        }

        return json(['code' => 0, 'msg' => '入驻失败']);
    }

    /**
     * 入驻店铺列表
     * @return \think\response\Json
     */
    function storeList()
    {
        $merchant_id = input('merchant_id', 0);
        $keyword = input('keyword', '');
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];

        if ($merchant_id) {
            $where[] = ['merchant_id', '=', $merchant_id];
        }

        if ($keyword) {
            $where[] = ['store_name|contact_name|contact_phone|street_address', 'like', '%' . $keyword . '%'];
        }

        $list = model\Store::where($where)->limit($skip, $limit)->order('create_time desc')->select();

        foreach ($list as &$item) {
            $item['store_logo'] = $item['store_logo'] ? replace_url($item['store_logo']) : replace_url('/static/images/logo.png');
            $item['status_str'] = CommonEnum::examineText($item['status']);
            $item['store_type_str'] = MerchantEnum::storeTypeText($item['user_type']);
        }

        $result = [
            'data' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 代理开启商户入驻权限
     * @return \think\response\Json
     */
    function openMerchantAuth()
    {
        $agent = model\Agent::get($this->user_id);
        $config = web_config('merchant_config');
        if (!$agent) {
            $agentAuth = false;
        } else {
            if ($agent['agent_level'] >= $config['agent_open_merchant_level']) {
                $agentAuth = true;
            } else {
                $agentAuth = false;
            }
        }

        $result = [
            'agent_level' => $agent['agent_level'] ?? 0,
            'open_level' => $config['agent_open_merchant_level'],
            'status' => $agentAuth,
        ];
        return json(['code' => 1, 'data' => $result]);
    }

}